* Tables 3 and 4 for Indonesia

use "temp/SI_clean.dta", clear
set more off
xtset id year
tsfill, full
bys year: egen sAGG  = total (misi)
bys year exporter: egen sAGGe = total(misi*exporter)
local t 97 
gen i = 0
replace i=1 if year==19`t'
gen mi0b = .
replace mi0b = mi * i
gen si0b = .
replace si0b = si * i
gen sAGG0b = sAGG * i
bys id: egen sAGG0 = total(sAGG0b)
bys id: egen mi0 = total(mi0b), missing
bys id: egen si0 = total(si0b), missing
drop mi0b si0b
gen deltas = si - si0
gen deltam = mi - mi0
gen misi0  = mi0 * si0 
gen NI = 0 // new importers
replace NI = 1 if (si>0 & si !=.) & (si0==0 | si0==.)
gen OI = 0 // firms that stop importing
replace OI = 1 if (si==0 | si ==.) & (si0>0 & si0 !=.)
gen CI=0 // continuing importers
replace CI =1 if si0>0 & si0!=. & si>0 & si!=.
gen withi = mi0 * deltas * CI
gen beti = si0 * deltam * CI
gen covi = deltas * deltam * CI

* Within
bys year: egen W  = total(withi) 
replace W = W / sAGG0 * 100
bys year: egen Wex1  = total(withi*exporter) 
replace Wex1 = Wex1 / sAGG0 * 100

* Between
bys year: egen B  = total(beti) 
replace B = B / sAGG0 * 100
bys year: egen Bex1  = total(beti*exporter)
replace Bex1 = Bex1 / sAGG0 * 100 // Exporter

* Covariance
bys year: egen C  = total(covi) 
replace C = C / sAGG0 * 100
bys year: egen Cex1  = total(covi*exporter) 
replace Cex1 = Cex1 / sAGG0 * 100 // Exporter

* Entry
bys year: egen E  = total(misi * NI) 
replace E = E / sAGG0 * 100
bys year: egen Eex1  = total(misi * NI*exporter) 
replace Eex1 = Eex1 / sAGG0 * 100 //  Exporter

* Exit
bys year: egen X  = total(misi0 * OI) 
replace X = X / sAGG0 * 100
bys year: egen Xex1  = total(misi0 * OI*exporter) 
replace Xex1 = Xex1 / sAGG0 * 100 // Exporter

collapse W Wex1 B Bex1 C Cex1 E Eex1 X Xex1 sAGG, by(year)
gen NE = E - X
gen NEEx1 = Eex1 - Xex1
gen All = W + B + C + E - X
drop E X Eex1 Xex1
label var W "Within"
label var B "Between"
label var C "Covariance"
label var NE "Net Entry"
label var All "Total"
replace W = round(W,0.01)
replace B = round(B,0.01)
replace C = round(C,0.01)
replace NE = round(NE,0.01)
replace All = round(All,0.01)
drop if year<1998
export excel year W B C NE All using "../../Output/Table3_Indo", first(varl) sh("Table3") replace

* Table 4:
gen BC = B+C
gen BCex1 = Bex1 + Cex1
label var BC "Between + Covariance"
label var NEEx1 "Net Entry: Exporters"
gen growthE = Wex1 + BCex1 + NEEx1
replace growthE = round(growthE,0.01)
replace BCex1 = round(BCex1,0.01)
replace NEEx1 = round(NEEx1,0.01)
label var All "Import Share Growth: Total"
label var growthE "Import Share Growth: Exporters"
export excel year All growthE BC BCex1 NE NEEx1 using "../../Output/Table4_Indo", first(varl) sh("Table4") replace
